package com.platform.base.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.base.domain.*;
import com.platform.base.mapper.*;
import com.platform.common.annotation.DataScope;
import com.platform.common.constant.UserConstants;
import com.platform.common.core.domain.Ztree;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.redis.RedisUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.platform.base.service.IBaseLocationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


/**
 * 住户信息Service业务层处理
 * 
 * @author wangqi
 * @date 2020-09-24
 */
@Service
public class BaseLocationServiceImpl extends ServiceImpl<BaseLocationMapper,BaseLocation> implements IBaseLocationService
{
    @Autowired
    private BaseLocationMapper baseLocationMapper;

    @Autowired
    private CollectorInfoMapper collectorInfoMapper;

    @Autowired
    private MeterInfoMapper meterInfoMapper;

    @Autowired
    private ValveInfoMapper valveInfoMapper;

    @Autowired
    private TempInfoMapper tempInfoMapper;

    /**
     * 查询住户信息列表
     * 
     * @param baseLocation 住户信息
     * @return 住户信息
     */
    @Override
    @DataScope(deptAlias = "s")
    public List<BaseLocation> selectBaseLocationList(BaseLocation baseLocation)
    {
        return baseLocationMapper.selectBaseLocationList(baseLocation);
    }

    /**
     * 查询住户信息列表
     *
     * @param baseLocation 住户信息
     * @return 住户信息
     */
    @Override
    @DataScope(deptAlias = "s")
    public List<BaseLocation> selectBaseLocationDataList(BaseLocation baseLocation)
    {
        return baseLocationMapper.selectBaseLocationDataList(baseLocation);
    }

    /**
     * 新增住户信息
     * 
     * @param baseLocation 住户信息
     * @return 结果
     */

    @Override
    @Transactional
    public int insertBaseLocation(BaseLocation baseLocation)
    {

        BaseLocation info = baseLocationMapper.selectById(baseLocation.getParentId());
        baseLocation.setAncestors(info.getAncestors() + "," + baseLocation.getParentId());
        baseLocation.setCreateTime(DateUtils.getNowDate());
        return baseLocationMapper.insert(baseLocation);
    }

    /**
     * 修改地址资料
     *
     * @param baseLocation 地址资料
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBaseLocation(BaseLocation baseLocation)
    {

        BaseLocation newParentLocation = baseLocationMapper.selectById(baseLocation.getParentId());
        baseLocation.setUpdateTime(DateUtils.getNowDate());
        BaseLocation oldLocation = baseLocationMapper.selectById(baseLocation.getLocationId());
        if (StringUtils.isNotNull(newParentLocation) && StringUtils.isNotNull(oldLocation))
        {
            String newAncestors = newParentLocation.getAncestors() + "," + newParentLocation.getLocationId();
            String oldAncestors = oldLocation.getAncestors();
            baseLocation.setAncestors(newAncestors);
            updateLocationChildren(baseLocation.getLocationId(), newAncestors, oldAncestors);
        }
        int result = baseLocationMapper.updateById(baseLocation);
        return result;
    }

    /**
     * 删除住户信息对象
     * 
     * @param id 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteBaseLocationById(Long id)
    {
        return baseLocationMapper.deleteById(id);
    }

    /**
     * 查询部门人数
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    @DataScope(deptAlias = "s")
    public int selectLocationCount(Long parentId)
    {
        return baseLocationMapper.selectCount(new QueryWrapper<BaseLocation>().eq("parent_id", parentId));
    }

    /**
     * 查询是否存在关联设备
     *
     * @param locationId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public int checkLocationExistEquipment(Long locationId)
    {
        int collectorCount = collectorInfoMapper.selectCount(new QueryWrapper<CollectorInfo>().eq("location_id",locationId));
        if(collectorCount > 0){
            return 1;
        }
        int valveCount = valveInfoMapper.selectCount(new QueryWrapper<ValveInfo>().eq("location_id", locationId));
        if(valveCount > 0){
            return 2;
        }
        int meterCount = meterInfoMapper.selectCount(new QueryWrapper<MeterInfo>().eq("location_id", locationId));
        if(meterCount > 0){
            return 3;
        }
        int tempCount = tempInfoMapper.selectCount(new QueryWrapper<TempInfo>().eq("location_id", locationId));
        if(tempCount > 0){
            return 4;
        }
        return 0;
    }

    /**
     * 校验住户信息是否唯一
     * @param baseLocation 住户信息
     * @return
     */
    @Override
    public String checkLocationNameUnique(BaseLocation baseLocation) {
        Long locationId = StringUtils.isNull(baseLocation.getLocationId()) ? 0L : baseLocation.getLocationId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("location_name",baseLocation.getLocationName());
        queryWrapper.eq("parent_id",baseLocation.getParentId());
        BaseLocation location = baseLocationMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(location) && location.getLocationId().longValue() != locationId.longValue())
        {
            return UserConstants.LOCATION_NAME_NOT_UNIQUE;
        }
        return UserConstants.LOCATION_NAME_UNIQUE;
    }
    /**
     * 修改子元素关系
     *
     * @param LocationId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateLocationChildren(Long LocationId, String newAncestors, String oldAncestors)
    {
        List<BaseLocation> children = baseLocationMapper.selectChildrenLocationById(LocationId);
        for (BaseLocation child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            baseLocationMapper.updateLocationChildren(children);
        }
    }

    /**
     * 查询住户管理树
     *
     * @return 所有住户信息
     */
    @Override
    @DataScope(deptAlias = "s", locationAlias = "b")
    public List<Ztree> selectLocationTree(BaseLocation baseLocation)
    {
        List<BaseLocation> locationList = baseLocationMapper.selectBaseLocationTreeList(baseLocation);
        List<Ztree> ztrees = initZtree(locationList);
        return ztrees;
    }

    /**
     * 查询住户管理树（排除下级）
     *
     * @param location 住户信息
     * @return 所有住户信息
     */
    @Override
    @DataScope(deptAlias = "d", locationAlias = "l")
    public List<Ztree> selectLocationTreeExcludeChild(BaseLocation location)
    {
        Long locationId = location.getLocationId();
        List<BaseLocation> locationList = baseLocationMapper.selectBaseLocationTreeList(location);
        Iterator<BaseLocation> it = locationList.iterator();
        while (it.hasNext())
        {
            BaseLocation d = (BaseLocation) it.next();
            if (d.getLocationId().intValue() == locationId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), locationId + ""))
            {
                it.remove();
            }
        }
        List<Ztree> ztrees = initZtree(locationList);
        return ztrees;
    }

    /**
     * 对象转住户树
     *
     * @param locationList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<BaseLocation> locationList)
    {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (BaseLocation location : locationList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(location.getLocationId());
            ztree.setpId(location.getParentId());
            ztree.setName(location.getLocationName());
            ztree.setTitle(location.getLocationName());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    /**
     * 导入住户信息
     * @param locationList 住户信息列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return
     */
    @Override
    public String importLocation(List<BaseLocation> locationList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(locationList) || locationList.size() == 0)
        {
            throw new BusinessException("导入住户信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseLocation location : locationList)
        {
            try
            {
                Long parentId = 0L;
                String ancestors = "";
                //String locationType = "00";

                //查询一级地址
                if(location.getParent1()!=null && !location.getParent1().equals("")){
                    BaseLocation f = baseLocationMapper.selectOne(new QueryWrapper<BaseLocation>().eq("location_name",location.getParent1()));
                    if (!StringUtils.isNull(f)) {
                        parentId = f.getLocationId();
                        ancestors = f.getAncestors() + "," + parentId;
                    }
                }
                //查询二级地址
                if(location.getParent2()!=null && !location.getParent2().equals("")){
                    BaseLocation f = baseLocationMapper.selectOne(new QueryWrapper<BaseLocation>().eq("location_name",location.getParent2()).eq("ancestors", ancestors));
                    if (!StringUtils.isNull(f)) {
                        parentId = f.getLocationId();
                        ancestors = f.getAncestors() + "," + parentId;
                    }
                }
                //查询三级地址
                if(location.getParent3()!=null && !location.getParent3().equals("")){
                    BaseLocation f = baseLocationMapper.selectOne(new QueryWrapper<BaseLocation>().eq("location_name",location.getParent3()).eq("ancestors", ancestors));
                    if (!StringUtils.isNull(f)) {
                        parentId = f.getLocationId();
                        ancestors = f.getAncestors() + "," + parentId;
                    }
                }
                //查询四级地址
                if(location.getParent4()!=null && !location.getParent4().equals("")){
                    BaseLocation f = baseLocationMapper.selectOne(new QueryWrapper<BaseLocation>().eq("location_name",location.getParent4()).eq("ancestors", ancestors));
                    if (!StringUtils.isNull(f)) {
                        parentId = f.getLocationId();
                        ancestors = f.getAncestors() + "," + parentId;
                    }
                }
                //查询五级地址
                if(location.getParent5()!=null && !location.getParent5().equals("")){
                    BaseLocation f = baseLocationMapper.selectOne(new QueryWrapper<BaseLocation>().eq("location_name",location.getParent5()).eq("ancestors", ancestors));
                    if (!StringUtils.isNull(f)) {
                        parentId = f.getLocationId();
                        ancestors = f.getAncestors() + "," + parentId;
                    }
                }
                location.setAncestors(ancestors);
                location.setParentId(parentId);
               // location.setLocationType(locationType);
                // 验证是否存在这个住户信息
                BaseLocation l = baseLocationMapper.selectOne(new QueryWrapper<BaseLocation>().eq("location_name",location.getLocationName()).eq("parent_id",location.getParentId()));
                if (StringUtils.isNull(l)) {
                    location.setCreateBy(operName);
                    location.setCreateTime(DateUtils.getNowDate());
                    this.insertBaseLocation(location);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、住户 " + location.getLocationName() + " 导入成功");
                } else if (isUpdateSupport) {
                    location.setUpdateBy(operName);
                    location.setUpdateTime(DateUtils.getNowDate());
                    location.setLocationId(l.getLocationId());
                    this.updateBaseLocation(location);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、住户 " + location.getLocationName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、住户 " + location.getLocationName() + " 已存在");
                }
            }
            catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、住户 " + location.getLocationName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    /**
     * 用户状态修改
     *
     * @param location 用户信息
     * @return 结果
     */
    @Override
    public int changeStatus(BaseLocation location)
    {
        return baseLocationMapper.updateUser(location);
    }
    /**
     * 用户状态修改
     *
     * @param location 用户信息
     * @return 结果
     */
    @Override
    public int changeAlarmStatus(BaseLocation location)
    {
        return baseLocationMapper.updateAlarm(location);
    }
    /**
     * 查询地址信息
     *
     * @param locationId 地址Id
     * @return 热表信息
     */
    @Override
    public BaseLocation selectBaseLocationById(String locationId){
        BaseLocation baseLocation = baseLocationMapper.selectBaseLocationById(locationId);
        return baseLocation;
    }
}
